<?php
declare(strict_types=1);

namespace app\admin\model;

use app\common\support\Password;
use LhpAmis\util\AmisConfig;
use think\model\concern\SoftDelete;

class Admin extends Base
{
    use SoftDelete;

    protected $name = 'system_admin';
    // 定义隐藏字段
    protected $hidden = ['password', 'password_salt', 'delete_time'];
    /**
     * 角色
     * @return \think\model\relation\BelongsToMany
     */
    public function groups(): \think\model\relation\BelongsToMany
    {
        return $this->belongsToMany(AuthGroup::class, 'system_auth_group_access', 'group_id', 'admin_id');
    }
    /**
     * 管理员设置
     * @return \think\model\relation\HasOne
     */
    public function admin_settings(): \think\model\relation\HasOne
    {
        return $this->hasOne(AdminSettings::class, 'admin_id', 'id');
    }
    /**
     * 创建前
     *
     * @param Admin $model
     *
     * @return mixed|void
     */
    public static function onBeforeInsert($model)
    {
        parent::onBeforeInsert($model);
        $model->create_ip = request()->ip();
        $model->create_time = time();
        $model->last_active = time();
        $model->last_ip = request()->ip();
    }

    /**
     * 更新前
     *
     * @param Admin $model
     *
     * @return mixed|void
     */
    public static function onBeforeUpdate($model)
    {
        parent::onBeforeUpdate($model);
        $model->last_active = time();
        $model->last_ip = request()->ip();
    }

    /**
     * 返回密码信息
     *
     * @param $password
     * @param string $salt
     *
     * @return array|string
     */
    public static function password($password, string $salt = '')
    {
        return (new Password())->withSalt(config('lhp.passport.password_salt'))->encrypt($password, $salt);
    }

    public function getAvatarAttr($value)
    {
        $url = Upload::where('id', $value)->value('url');
        if (!$url) {
            $url = AmisConfig::get('frame_image') ?? '';
        }
        return $url;
    }
    // public function setAvatarAttr($value)
    // {
    //     $url = Upload::whereLike('url', "%{$value}%")->value('id');
    //     if (!$url) {
    //         $url = 0;
    //     }
    //     return $url;
    // }
}
